package ece1779.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.Vector;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import com.amazonaws.services.cloudwatch.model.ListMetricsRequest;
import com.amazonaws.services.cloudwatch.model.ListMetricsResult;
import com.amazonaws.services.cloudwatch.model.Metric;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeInstanceAttributeResult;
import com.amazonaws.services.ec2.model.DescribeInstanceStatusRequest;
import com.amazonaws.services.ec2.model.DescribeInstanceStatusResult;
import com.amazonaws.services.ec2.model.InstanceState;
import com.amazonaws.services.ec2.model.InstanceStatus;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;

import org.im4java.core.*;

public class ManagerUI extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
  
        cloudWatchShowWorkers(out,request,response);
        
     }
    
       
    void cloudWatchShowWorkers(PrintWriter out,HttpServletRequest request, HttpServletResponse response) throws IOException {
    	
    	
    	BasicAWSCredentials awsCredentials = (BasicAWSCredentials)getServletContext().getAttribute("AWSCredentials");
		
        AmazonEC2Client ec2 = (AmazonEC2Client) new AmazonEC2Client(awsCredentials);
        AmazonCloudWatch cw = new AmazonCloudWatchClient(awsCredentials);

        try {
        	
        	DescribeInstanceStatusRequest desc = new DescribeInstanceStatusRequest();
        	DescribeInstanceStatusResult result = ec2.describeInstanceStatus(desc);
        	List<InstanceStatus> stateList  = (List<InstanceStatus>) result.getInstanceStatuses();
        	List<String> instanceNames = new ArrayList<String>();
        	List<Datapoint> instancData = new ArrayList<Datapoint>();
        	List<String> htmlInstanceStrings = new ArrayList<String>();
        	out.print("<p>");

        	for (int i = 0 ; i < stateList.size(); i++) {
        		InstanceStatus status = stateList.get(i);
        		instanceNames.add(status.getInstanceId());
        		
        		GetMetricStatisticsRequest req = new GetMetricStatisticsRequest();
            	req.setMetricName("CPUUtilization");
            	req.setNamespace("AWS/EC2");
            	Dimension dim = new Dimension();
            	dim.setName("InstanceId");
            	dim.setValue(status.getInstanceId());
            	List<Dimension> dimList = new ArrayList<Dimension>();
            	dimList.add(dim);            	
            	req.setDimensions(dimList);
            	
            	Date endTime = new Date();
            	Date startTime = new Date();
            	startTime.setTime(endTime.getTime()-1200000);
            	req.setStartTime(startTime);
            	req.setEndTime(endTime);
            	req.setPeriod(60);
            	Vector<String>statistics = new Vector<String>();
            	statistics.add("Maximum");
            	statistics.add("Average");
            	req.setStatistics(statistics);
            	GetMetricStatisticsResult stats = cw.getMetricStatistics(req);
            	List<Datapoint> dataPointsList = stats.getDatapoints();
            	StringBuilder jspOutString = new StringBuilder();
            	jspOutString.append("Instance Name = " + status.getInstanceId());

            	if(dataPointsList.size() > 0) {
            		Datapoint dPoint = dataPointsList.get(0);
            		jspOutString.append(" Data Recorded at " + dPoint.getTimestamp() );
            		jspOutString.append(" Maximum Percent = "+dPoint.getMaximum());
            		jspOutString.append(" Average Percent = "+dPoint.getAverage());
            		instancData.add(dataPointsList.get(0));
            	} else {
            		Datapoint emptyPoint = new Datapoint();
            		instancData.add(emptyPoint);
            		jspOutString.append(" Information is currently not availabe for this instance");
            	}
            	
            	htmlInstanceStrings.add(jspOutString.toString());
        	}
        	
		    request.setAttribute("instanceInfo", htmlInstanceStrings );
		    request.getRequestDispatcher("/jsp/ManagerUI.jsp").forward(request, response);
        }  	
        catch(Exception ex) {
  		  response.getWriter().println(ex.getMessage());
          //getServletContext().log(ex.getMessage());  
        }  

    }
    
}